package com.wjw.rabbitdemo.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Bean
    public MessageConverter messageConverter(){
        //转换成json类型的数据
        return new Jackson2JsonMessageConverter();
    }
    //MyRabbitConfig对象创建完成后，执行这个方法
    @PostConstruct
    public void initRabbitTemple(){
        //设置确认回调
        //confirm 消息发送到rabbitmq broker后回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * @param correlationData  当前消息的唯一关联数据（唯一id
             * @param ack               rabbitmq是否成功收到，成功为true
             * @param cause              失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("correlationData:"+correlationData);
                System.out.println("ack"+ack);
                System.out.println("cause"+cause);
            }
        });
        //设置消息抵达队列的确认回调
        /**
         * Message 投递失败的消息
         * replyCode 回复的状态码
         * replyText    回复的文本内容
         * exchange routingKey 当时这个消息用的哪个路由键，发给哪个交换机
         */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("消息抵达队列的确认回调");
            }
        });
        //过时后新写法
        //rabbitTemplate.setReturnsCallback(System.out::println);
    }
}
